package com.chat.http.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chat.constant.tab.MessageConstant;
import com.chat.entity.TdChatGroup;
import com.chat.http.service.GroupManageService;
import com.chat.http.validator.GroupManageVoValidator;
import com.chat.vo.params.ExceptionVo;
import com.chat.vo.params.GroupParametersVo;
import com.chat.websocket.service.GroupChatService;
import com.chat.websocket.service.LeaveMsgService;

/**
 * 群聊
 * 
 * @author lwh
 *
 */
@Controller
@RequestMapping("/group")
public class GroupManageController {
	private static final Logger logger = Logger.getLogger(GroupManageController.class);

	@Autowired
	private GroupManageVoValidator thisValidator;

	@Autowired
	private GroupManageService groupManageService;

	@Autowired
	private GroupChatService groupChatService;

	@Autowired
	private LeaveMsgService leaveMsgService;

	/**
	 * 用户建群(参照微信群，无需对方同意)
	 * 
	 * @param request
	 * @param gmv
	 * @param result
	 * @return
	 * @throws ExceptionVo
	 * @throws IOException
	 */
	@RequestMapping(value = "/create")
	@ResponseBody
	public Map<String, String> CreateGroup(HttpServletRequest request, GroupParametersVo gmv, BindingResult result)
			throws ExceptionVo, IOException {
		logger.info("进入建群Controller");
		Map<String, String> map = new HashMap<String, String>(0);
		thisValidator.createGroupValidate(gmv, result);
		if (result.hasErrors()) {
			map.put("status", "error");
			map.put("msg", result.getAllErrors().get(0).getCode());
			return map;
		} else {
			// 建群业务
			TdChatGroup group = groupManageService.createGroup(gmv.getUserName(), gmv.getInviteUsers(),
					gmv.getGroupName());
			logger.info("已建群：" + group);
			if (null != group) {
				// ws推送业务, 返回离线用户
				StringBuffer leaveUsers = groupChatService.pushCreateGroupMsg(group);
				// 把离线信息存储入库
				leaveMsgService.saveLeaveMsg(MessageConstant.Group, MessageConstant.BodyType_Text,
						"群创建时间为" + group.getCreatetime(), group.getGroupadmin(), leaveUsers.toString(),
						group.getCreatetime());

				map.put("status", "success");
				return map;
			}
			map.put("status", "error");
			map.put("msg", "禁止邀请非好友加群");
			return map;
		}
	}

	/**
	 * 获取“群”详情(http)
	 * 
	 * @param groupid
	 */
	public void getGroupDetails(String groupid) {

	}

	/**
	 * 修改群信息(群名称、群头像、群主)(http + ws)
	 */
	public void modifyGroupDetails() {

	}

	/**
	 * 移除群成员(包括解散群)(http不通知)
	 */
	public void moveGroupMan() {

	}

	/**
	 * 获取个人拥有的所有群信息列表
	 */
	public void getAllGroupsForOwn() {

	}

	/**
	 * 发送群信息(http+ws)
	 */
	public void sendGroupMsg() {

	}

}
